package com.example.student.web.user;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.UUID;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.student.entity.User;
import com.example.student.util.MyBeanUtil;
import com.example.student.util.Pager;
import com.example.student.web.BaseServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author TonySong
 * @date 2025/8/7 0007
 * @time 19:57
 */
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends BaseServlet {



    public String toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return  PREFIX+"login"+SUFFIX;
    }

    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            User user=new User();
            MyBeanUtil.copyProperties(user,request.getParameterMap());
            User logUser=this.userService.login(user);
        System.out.println("###########################"+logUser);
            if(!Objects.isNull(logUser)){
                HttpSession session = request.getSession();
                session.setAttribute("logUser",logUser);
                return "redirect:userList";
            }else{
                request.setAttribute("msg","<font color='red'>对比起，错误的账号或密码，登录失败！</font>");
                return  PREFIX+"login"+SUFFIX;
            }
    }

    public String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           HttpSession session = request.getSession();
           if(session.getAttribute("logUser")!=null){
               session.removeAttribute("logUser");
           }
           return "redirect:toLogin";
    }

    public String userList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String size=request.getParameter("pagesize");
        size = size == null ? "5": size;
        Integer pagesize= Integer.parseInt(size);
        String currentPage=request.getParameter("currentPage");
        Pager<User> pager= this.userService.pageUsers(currentPage,pagesize);
        pager.setPagesize(pagesize);
        pager.setUrl("user?action=userList");
        request.setAttribute("pager",pager);
        return PREFIX+"user_list"+SUFFIX;
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
         boolean flag=this.userService.delete(Integer.parseInt(id));
        PrintWriter printWriter = response.getWriter();
        printWriter.print(flag);

    }

    public void export(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取所有
        List<User> users = this.userService.findAll();
        ExcelWriter excelWriter = ExcelUtil.getWriter();
        excelWriter.write(users,true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode("员工信息", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        excelWriter.flush(out,true);
        excelWriter.close();
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //上传头像
        Part part = request.getPart("pic");
        String fileName = UUID.fastUUID().toString(true);
        String name =part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf(".")+1);
        fileName = fileName+"."+name;
        System.out.println(fileName);
        String realPath = request.getServletContext().getRealPath("/upload/");
        File file=new File(realPath);
        if(file.isDirectory()){
            if(!file.exists()){
                file.mkdir();
            }
        }
        System.out.println("服务器的路径是："+realPath);
        part.write(realPath+ File.separator +fileName);
        //保存用户信息到数据库
        Map<String, String[]> map = request.getParameterMap();
        User user=new User();
        MyBeanUtil.copyProperties(user,map);
        user.setAvatar(fileName);
        boolean flag=false;
        if(Objects.isNull(user.getId())){
            //如果不存在id则执行新增
            flag=this.userService.add(user);
        }else{
            //如果id存在则还行保存
            flag=this.userService.update(user);
        }
        return flag ?  "redirect:userList" : "redirect:toAdd";
    }



    public void hasUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           String username=request.getParameter("username");
           PrintWriter printWriter = response.getWriter();
           printWriter.print(this.userService.hasUsername(username));
           printWriter.close();
    }
}
